import getopt
import os
import sys
import time
import hmac
import hashlib
import base64
import json
import urllib.parse
import urllib3
import jenkins
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def get_test_case():
    try:
        opts, args = getopt.getopt(sys.argv, '-h')
        if len(args) < 3:
            raise ValueError("Not enough command line arguments")
        return args[1], args[2], args[3]
    except getopt.GetoptError as err:
        logging.error(f"Error parsing arguments: {err}")
        sys.exit(2)


def generate_dingding_sign(secret):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = f'{timestamp}\n{secret}'.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign


def send_dingtalk_message(url, message):
    try:
        urllib3.disable_warnings()
        http = urllib3.PoolManager()
        jd = json.dumps(message)
        response = http.request('POST', url, body=jd.encode('utf-8'), headers={'Content-Type': 'application/json'})
        response_data = json.loads(response.data.decode('utf-8'))

        if response.status == 200 and response_data.get("errcode") == 0:
            logging.info("DingTalk message sent successfully.")
        else:
            logging.error(f"Failed to send message to DingTalk: {response_data}")
    except Exception as e:
        logging.error(f"Failed to send message to DingTalk: {e}")


def main():
    # 获取命令行参数
    env, flow, test_name = get_test_case()

    # 钉钉配置
    secret = "SEC45cce3517cc70e69cc6f8aa7b55cc0bfc5f464e7d07a7bbfce6e43d264d57aba"  # 从环境变量获取secret
    token = "dcf75077d4192eda6e74820b999bc44f1dbfc76386046bc1996714f54861b71f"
    timestamp, sign = generate_dingding_sign(secret)
    dingding_url = f'https://oapi.dingtalk.com/robot/send?access_token={token}&timestamp={timestamp}&sign={sign}'

    # Jenkins配置
    jenkins_url = os.getenv('JENKINS_URL', 'http://192.168.61.130:8080/')
    jenkins_user = os.getenv('JENKINS_USER', 'admin')
    jenkins_pass = os.getenv('JENKINS_PASS', 'admin')
    server = jenkins.Jenkins(jenkins_url, username=jenkins_user, password=jenkins_pass)

    job_name = f"/job/{test_name}/"
    job_url = f"{jenkins_url}{job_name}"
    job_last_build_url = server.get_info(job_name)['lastBuild']['url']
    report_url = f"{job_last_build_url}allure"

    # 读取测试数据
    try:
        d = {}
        file_path = f'/root/.jenkins/workspace/{test_name}/allure-report/export/prometheusData.txt'
        with open(file_path, 'r') as f:
            for lines in f:
                launch_name, num = lines.strip().split(' ')
                d[launch_name] = num
        retries_run = d.get('launch_retries_run', '0')
        status_passed = d.get('launch_status_passed', '0')
        status_failed = d.get('launch_status_failed', '0')
        pass_rate = "%.f%%" % (float(status_passed) / float(retries_run) * 100) if retries_run != '0' else '0%'
    except Exception as e:
        logging.error(f"Error reading report data: {e}")
        return

    # 构建钉钉消息
    message = {
        "msgtype": "text",
        "text": {
            "content": f"Pytest_Allure_{test_name}自动化脚本执行完成。\n"
                       f"测试概述:\n运行总数: {retries_run}\n通过数量: {status_passed}\n失败数量: {status_failed}\n通过率: {pass_rate}\n"
                       f"构建地址：{job_url}\n报告地址：{report_url}"
        },
        "at": {
            "atMobiles": ["130xxxxxxxx"],
            "isAtAll": 1
        }
    }

    # 发送钉钉通知
    send_dingtalk_message(dingding_url, message)


if __name__ == "__main__":
    main()
